package com.example.wuqujingdianphone.fragment.bookcity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.activity.BookDetailActivity;
import com.example.wuqujingdianphone.activity.BookSearchActivity;
import com.example.wuqujingdianphone.activity.BookSortListActivity;
import com.example.wuqujingdianphone.activity.TuShuFenLeiListActivity;
import com.example.wuqujingdianphone.adapter.BCBookAdapter;
import com.example.wuqujingdianphone.adapter.BookToTalAdapter;
import com.example.wuqujingdianphone.adapter.BookTotalBean;
import com.example.wuqujingdianphone.adapter.BookTypeAdapter;
import com.example.wuqujingdianphone.adapter.SectionFenleiAdapter;
import com.example.wuqujingdianphone.adapter.SectionTingshuAdapter;
import com.example.wuqujingdianphone.api.ApiConfig;
import com.example.wuqujingdianphone.base.BaseFragment;
import com.example.wuqujingdianphone.bean.BookListBean2;
import com.example.wuqujingdianphone.bean.BookSortBean;
import com.example.wuqujingdianphone.bean.MySectionFenleiBean;
import com.example.wuqujingdianphone.bean.MySectionFenleiChildBean;
import com.example.wuqujingdianphone.bean.MySectionTingshuBean;
import com.example.wuqujingdianphone.bean.MySectionTingshuChildBean;
import com.example.wuqujingdianphone.bean.TingshuHomeBean;
import com.example.wuqujingdianphone.bean.TuShuFenlei;
import com.example.wuqujingdianphone.utils.FullyGridLayoutManager;
import com.example.wuqujingdianphone.utils.GsonUtil;
import com.example.wuqujingdianphone.utils.NiceDialogUtils;
import com.example.wuqujingdianphone.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.CacheMode;
import com.vise.xsnow.http.mode.CacheResult;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by 29083 on 2018/4/10.
 * <p>
 * 书城--图书
 */

public class BookCityBookFragment extends BaseFragment implements SectionFenleiAdapter.HeaderCallBack, BaseQuickAdapter.OnItemClickListener {
    private static final String TAG = "BookCityBookFragment";
    @BindView(R.id.btn_search)
    LinearLayout mBtnSearch;
    @BindView(R.id.all_book)
    TextView mAllBook;
    @BindView(R.id.recyclerView2)
    RecyclerView mRecyclerViewSort;


    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private BookToTalAdapter mAdapter;
    private List<BookTotalBean.ListBean> totalList = new ArrayList<>();

    private boolean isFirstLoadDate;

    private BookTypeAdapter typeAdapter;

    private List<MySectionFenleiBean> mData = new ArrayList<>();
    private SectionFenleiAdapter sectionAdapter;
    private List<TuShuFenlei> secondList = new ArrayList<>();
    private int page = 1;

    public static BookCityBookFragment getBookCityBookFragment() {
        BookCityBookFragment fragment = new BookCityBookFragment();
        return fragment;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_shop_book, null);
        return view;
    }

    private View getFooterView(View.OnClickListener listener) {
        View footerView = getActivity().getLayoutInflater().inflate(R.layout.foot_view_layout, (ViewGroup) mRecyclerView.getParent(), false);
        footerView.setOnClickListener(listener);
        return footerView;
    }


    private void initView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mAdapter = new BookToTalAdapter(getActivity(), null);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.addFooterView(getFooterView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page++;
                showLoading(getActivity());
                getTotalData(page, true);

            }
        }));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i(TAG, "onItemClick: position=" + position);


                Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                intent.putExtra("bookId", totalList.get(position).getId());
                intent.putExtra("bookTitle", totalList.get(position).getNews_tit());
                startActivity(intent);

            }
        });

        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), BookSearchActivity.class));

            }
        });

        mRecyclerViewSort.setLayoutManager(new FullyGridLayoutManager(getActivity(), 3));
        mRecyclerViewSort.setHasFixedSize(true);
        mRecyclerViewSort.setNestedScrollingEnabled(false);
        // mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));
        sectionAdapter = new SectionFenleiAdapter(R.layout.item_book_list, R.layout.def_section_head, mData);
        sectionAdapter.setOnItemClickListener(this);
        mRecyclerViewSort.setAdapter(sectionAdapter);
        sectionAdapter.setHeaderCallBack(this);
    }

    @Override
    protected void initData() {
        Log.i(TAG, "initData: ");
        isFirstLoadDate = true;
        initView();
    }

    @Override
    protected void lazyLoad() {
        Log.i(TAG, "lazyLoad: ");
        if (isFirstLoadDate) {
            isFirstLoadDate = false;
            showLoading(getActivity());
            getTotalData(page, false);
        }
    }

    private List<BookListBean2> newListBean2s;//新的列表集合，为加载更多服务
    private List<BookListBean2> allCacheData;//全部数据


    private void getTotalData(final int mPage, final boolean isLoadMore) {
        // showLoading(getActivity());
        OkGo.<String>get(ApiConfig.APP_URL + "index.php/jiekou/getBookByPage")
                .tag(this)
                .params("pageIndex", String.valueOf(mPage))
                .params("pageSize", String.valueOf(6))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        cancelLoading();
                        String sdsa = response.body();
                        BookTotalBean bean = GsonUtil.GsonToBean(sdsa, BookTotalBean.class);

                        totalList.addAll(bean.getList());
//                        if (isLoadMore) {
//                            mAdapter.addData(totalList);
//                            mRecyclerView.setHasFixedSize(true);
//                            mRecyclerView.setNestedScrollingEnabled(false);
//                        } else {
                        mAllBook.setText("全部图书（" + bean.getTotal() + "）");
                        mAdapter.setNewData(totalList);
//                        }
                        getData("分类");
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        cancelLoading();
                        ToastUtil.show("" + response.getException().getMessage());
                    }
                });

    }

    private void getData(String type) {
        showLoading(getActivity());
        OkGo.<String>get(ApiConfig.APP_URL + "/index.php/jiekou/getBookClass")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        cancelLoading();
                        String sdsa = response.body();
                        secondList.clear();
                        secondList = GsonUtil.getObjectList(response.body(), TuShuFenlei.class);
                        getData();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        cancelLoading();
                        ToastUtil.show("" + response.getException().getMessage());
                    }
                });

    }

    private void getData() {
        for (int k = 0; k < secondList.size(); k++) {
            mData.add(new MySectionFenleiBean(true, secondList.get(k).getName(), secondList.get(k).getId(), true));
            for (int w = 0; w < secondList.get(k).getChilds().size(); w++) {
                mData.add(new MySectionFenleiBean(new MySectionFenleiChildBean(secondList.get(k).getChilds().get(w).getId(),
                        String.valueOf("http://www.wenqujingdian.com" + secondList.get(k).getChilds().get(w).getSpic()),
                        secondList.get(k).getChilds().get(w).getNews_tit(), false)));
            }
        }

        sectionAdapter.notifyDataSetChanged();
    }


    @Override
    public void headerclick(String id, String title) {
        Intent intent = new Intent(getActivity(), TuShuFenLeiListActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("title", title);
        startActivity(intent);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Log.i(TAG, "onItemClick: position=" + position);
        if (!mData.get(position).isHeader) {
            Intent intent = new Intent(getActivity(), BookDetailActivity.class);
            intent.putExtra("bookId", mData.get(position).t.getId());
            intent.putExtra("bookTitle", mData.get(position).t.getName());
            startActivity(intent);
        }
    }
}
